package com.dushuren.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.mapper.TagMapper;
import com.dushuren.project.model.entity.Tag;
import com.dushuren.project.service.TagService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.dushuren.project.constant.TagConstant.TAG_CATEGORY_PROJECT;
import static com.dushuren.project.constant.TagConstant.TAG_CATEGORY_TECHNOLOGY;

/**
* @author qieqie
* @description 针对表【tag(标签表)】的数据库操作Service实现
* @createDate 2022-10-17 09:40:58
*/
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
    implements TagService {

  @Resource
  TagMapper tagMapper;

  /**
   * 校验tag中的 Category 是否存在 存在则将队员tagName的值返回
   */
  @Override
  public List<Tag> inspectTagCategory(String category) {
	if (category == null) {
	  throw new BusinessException(ErrorCode.NULL_ERROR);
	}
	QueryWrapper<Tag> queryWrapperTag = new QueryWrapper<>();
	queryWrapperTag.select("tagName");
	queryWrapperTag.eq("category", category);
	return tagMapper.selectList(queryWrapperTag);
  }

  /***
   * 校验 Category 和 tagName 的标签是否存在。
   */
  @Override
  public Boolean checkTeamTags(String teamType, String teamTechnologyType) {
	List<String> tagsProject = this.inspectTagCategory(TAG_CATEGORY_PROJECT).stream().map(Tag::getTagName).collect(Collectors.toList());
	boolean resultProject = tagsProject.contains(teamType);
	if (!resultProject) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR);
	}
	// JSON 转换为 java
	Gson gson = new Gson();
	Set<String> tmpTagNameSet = gson.fromJson(teamTechnologyType, new TypeToken<Set<String>>(){}.getType());
	List<String> tagsTechnology = this.inspectTagCategory(TAG_CATEGORY_TECHNOLOGY).stream().map(Tag::getTagName).collect(Collectors.toList());
	boolean resultTechnology = new HashSet<>(tagsTechnology).containsAll(tmpTagNameSet);
	if (!resultTechnology) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR);
	}
	return true;
  }
}




